/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.tukano.odt;

import it.tukano.fun.Tuple2;
import it.tukano.lang.StringExt;
import it.tukano.swingdeco.controls.JCheckBoxExt;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * A check box that if un-selected erases a paragraph from the content.xml file of
 * a odt document
 * @author utente4
 */
public class OdtOptionalParagraphEditor extends OdtFieldEditor {
    
    //Default serial version code
    private static final long serialVersionUID = 0;
    
    private final JCheckBoxExt box = new JCheckBoxExt();
    private final boolean defaultValue;

    public OdtOptionalParagraphEditor(Integer size, String label, StringExt defaultValue) {
        box.setText(label);
        this.defaultValue = defaultValue == null ? false : defaultValue.toBoolean(false);
        add(box);
        box.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                final boolean set = box.isSelected();
                final OdtField owner = getOwner();
                final StringExt OFF = StringExt.wrap("false");
                if(owner != null && owner.hasContext()) {
                    final OdtFieldContext context = owner.getContext();
                    for(StringExt excluded : owner.getExclusionList()) {
                        final OdtField exfield = context.getField(excluded.toString());
                        if(exfield != null && exfield.hasEditor()) {
                            OdtFieldEditor editor = exfield.getEditor();
                            editor.setValue(OFF);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void setValue(StringExt t) {
        box.setSelected(t.toBoolean(false));
    }

    @Override
    public Tuple2<StringExt, String> applyEditorValue(OdtField odtField, String xml) {
        if(odtField != null && xml != null && box.isSelected() == false) {
            xml = odtField.eraseWrappingParagraph(xml);
            return Tuple2.newInstance(new StringExt(""), xml);
        }
        return Tuple2.newInstance(StringExt.wrap(""), xml);
    }

    @Override
    public void clearValue() {
        box.setSelected(defaultValue);
    }
    
}
